import {AfterContentInit, AfterViewInit, Component, OnInit} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {AssessPriceService} from '../../assess-price.service';
import {NzMessageService} from 'ng-zorro-antd/message';
import {LoveRecycManageService} from '../../love-recyc-manage.service';
import {JSON} from 'tinymce';
import {NzModalService} from 'ng-zorro-antd/modal';
import {CommonService} from '../../../../services-common/common.service';
import {pipe} from 'rxjs';
import {tap} from 'rxjs/operators';
import {formatDate} from '@angular/common';

@Component({
  selector: 'app-assess-type-manage-list',
  templateUrl: './assess-type-manage-list.component.html',
  styleUrls: ['./assess-type-manage-list.component.scss']
})
export class AssessTypeManageListComponent implements OnInit {

  constructor(
    private router: Router,
    private assessPriceService: AssessPriceService,
    private nzMessageService: NzMessageService,
    private loveRecycManageService: LoveRecycManageService,
    private activatedRoute: ActivatedRoute,
    private nzModalService: NzModalService,
    private commonService: CommonService,
  ) {
  }

  static updateCache: () => void;
  // 查询条件
  query = {
    typeName: '',
    brand: '',
    department: '',
    evalStatus: '',
    template: '',
    remarks: '',
    date: [],
    // 当前页
    page: 1,
    // 分页大小
    pageSize: 20,
  };
  // 表格数据
  listOfData = {
    page: 1,
    total: 100,
    records: []
  };
  // 品牌列表
  brandOptions: any[] = [];
  // 系列列表
  departmentOptions: any[] = [];
  // 机型列表
  typeOptions: any[] = [];
  // 待选模版列表
  templateOptions: any[] = [];
  // 预览模态框显隐
  previewAssessTypeVisible = false;
  // 预览所需数据
  formData: any;
  customList: any;
  fixedPriceList: any;
  optionsRelationPrice: any;
  questionList: any;
  baseQuestion: any = {
    questionId: '',
    options: []
  };
  copyAssessTypeModal = {
    visible: false,
    data: {},
    brandId: '',
    id: '',
    seriesId: '',
    departmentOptions: [],
    typeOptions: [],
  };

  exportBenchmarkPriceLoading = false;

  ngOnInit(): void {
    const templateId = this.activatedRoute.snapshot.queryParams?.templateId;
    if (templateId) {
      // @ts-ignore
      this.query.template = templateId * 1;
    }
    this.getTableData();
    this.assessPriceService.getTemplateOptions().then((res: any) => {
      if (res.code === 0) {
        this.templateOptions = res.data;
      }
    });
    this.loveRecycManageService.getRecycleBrandList({page: 1, pageSize: 9999}).then((res: any) => {
      if (res.code === 0) {
        this.brandOptions = res.data.records;
      }
    });

    AssessTypeManageListComponent.updateCache = () => {
      this.getTableData();
    };
  }

  // 设置系列待选项
  setDepartmentOptions(id: any) {
    this.departmentOptions = [];
    this.query.department = '';
    if (!id) {
      return;
    }
    this.loveRecycManageService.getRecycleSeriesList({brandId: id, page: 1, pageSize: 9999}).then((res: any) => {
      if (res.code === 0) {
        this.departmentOptions = res.data.records;
      }
    });
  }


  onPageIndexChange(index: number) {
    this.query.page = index;
    this.getTableData();
  }

  onPageSizeChange(pageSize: number) {
    this.query.pageSize = pageSize;
    this.getTableData();
  }

  queryBtn() {
    this.query.page = 1;
    this.getTableData();
  }

  getTableData(
    page = this.query.page,
    pageSize = this.query.pageSize,
    name = this.query.typeName,
    brandId = this.query.brand,
    seriesId = this.query.department,
    evalId = this.query.template,
    remarks = this.query.remarks,
    evalStatus = this.query.evalStatus,
    startTime = this.assessPriceService.formatTime(this.query.date[0], 'date'),
    endTime = this.assessPriceService.formatTime(this.query.date[1], 'date')) {
    this.assessPriceService.getTypeAssessList(page, pageSize, name, brandId, seriesId, evalId, evalStatus, remarks, startTime, endTime).then((res: any) => {
      console.log(res);
      if (res.code === 0) {
        this.listOfData = res.data;
      } else {
        this.nzMessageService.error(res.message);
      }
    }).catch(() => {
      this.nzMessageService.error('查询列表异常');
    });
  }


  resetCondition() {
    this.query = {
      typeName: '',
      brand: '',
      evalStatus: '',
      department: '',
      template: '',
      remarks: '',
      date: [],
      page: 1,
      pageSize: 20,
    };
    this.queryBtn();
  }

  // 去新增
  gotoPage() {
    this.router.navigate(['aisi-recyc/assessTypeManageEdit'], {queryParams: {operationType: 'add'}});
  }

  // 去修改
  modify(data: any) {
    this.router.navigate(['aisi-recyc/assessTypeManageEdit'], {
      queryParams: {
        operationType: 'modify',
        assessTypeInfo: JSON.stringify(data)
      }
    });
  }

  // 去查看
  viewAssessType(data: any) {
    this.router.navigate(['aisi-recyc/assessTypeManageEdit'], {
      queryParams: {
        operationType: 'view',
        assessTypeInfo: JSON.stringify(data)
      }
    });
  }

  // 删除行
  deleteRow(data: any) {
    this.assessPriceService.deleteTypeAssess({
      id: data.id,
      evalStatus: data.evalStatus,
      evaluationId: data.evaluationId,
      evalId: data.evalId
    }).then((res: any) => {
      if (res.code === 0) {
        this.nzMessageService.success('删除成功');
        this.getTableData();
      } else {
        this.nzMessageService.error(res.message);
      }
    }).catch(() => {
      this.nzMessageService.error('删除异常');
    });

  }

  preview(data: any) {
    this.formData = {};
    this.customList = [];
    this.optionsRelationPrice = [];
    this.questionList = [];

    this.formData.brandName = data.brandName;
    this.formData.departmentName = data.seriesName;
    this.formData.typeName = data.name;
    this.formData.templateName = data.evalName;
    this.formData.remark = data.remarks;
    this.formData.usedBasePrice = data.secondHandPrice;
    this.formData.newBasePrice = data.newPrice;
    // this.customList = JSON.parse(data.modelContext).customList;
    this.baseQuestion = JSON.parse(data.modelContext).baseQuestion;
    // this.optionsRelationPrice = JSON.parse(data.modelContext).questionRelation;
    // this.fixedPriceList = JSON.parse(data.modelContext).fixedPrice || [];
    // this.templateOptions.forEach((q: any) => {
    //   if (q.id === data.evalId) {
    //     this.questionList = JSON.parse(q.context);
    //   }
    // });
    this.questionList = JSON.parse(data.mouldContext);
    this.previewAssessTypeVisible = true;
    console.log(JSON.parse(data.mouldContext));
  }

  changeStatus(data: any, evalStatus: number) {
    this.assessPriceService.addAndModifyTypeAssess(
      data.newPrice,
      data.secondHandPrice,
      data.evalId,
      data.evaluationId,
      data.remark,
      evalStatus,
      data.modelContext,
      data.id,
      false
    ).then((res: any) => {
      if (res.code === 0) {
        this.nzMessageService.success('操作成功');
        this.getTableData();
      } else {
        this.nzMessageService.error(res.message);
      }
    }).catch(() => {
      this.nzMessageService.error('操作异常');
    });

  }

  copyAssessType(data: any) {
    this.setCopyDepartmentOptions(data.brandId);
    this.setCopyTypeOptions(data.seriesId);
    this.copyAssessTypeModal = {
      visible: true,
      data,
      brandId: data.brandId,
      id: data.id,
      seriesId: data.seriesId,
      departmentOptions: [],
      typeOptions: [],
    };
  }

  hideAssessTypeModal() {
    this.copyAssessTypeModal = {
      visible: false,
      data: {},
      brandId: '',
      id: '',
      seriesId: '',
      departmentOptions: [],
      typeOptions: [],
    };
  }

  saveAssessTypeModal() {
    if (!this.copyAssessTypeModal.id) {
      this.nzMessageService.error('请选择机型');
      return;
    }
    this.assessPriceService.addAndModifyTypeAssess(
      // @ts-ignore
      this.copyAssessTypeModal.data.newBasePrice,
      // @ts-ignore
      this.copyAssessTypeModal.data.usedBasePrice,
      // @ts-ignore
      this.copyAssessTypeModal.data.evalId,
      '',
      // @ts-ignore
      this.copyAssessTypeModal.data.remarks,
      0,
      // @ts-ignore
      this.copyAssessTypeModal.data.modelContext,
      this.copyAssessTypeModal.id,
      true
    ).then((res: any) => {
      if (res.code === 0) {
        this.nzMessageService.success('操作成功');
        this.hideAssessTypeModal();
        this.getTableData();
      } else {
        this.nzMessageService.error(res.message);
      }
    }).catch(() => {
      this.nzMessageService.error('操作异常');
    });
  }

  // 设置系列待选项
  setCopyDepartmentOptions(id: any) {
    this.copyAssessTypeModal.typeOptions = [];
    this.copyAssessTypeModal.id = '';
    this.copyAssessTypeModal.departmentOptions = [];
    this.copyAssessTypeModal.seriesId = '';
    if (!id) {
      return;
    }
    this.loveRecycManageService.getRecycleSeriesList({brandId: id, page: 1, pageSize: 9999}).then((res: any) => {
      if (res.code === 0) {
        this.copyAssessTypeModal.departmentOptions = res.data.records;
      }
    });
  }

  // 设置机型待选项
  setCopyTypeOptions(id: any) {
    this.copyAssessTypeModal.typeOptions = [];
    this.copyAssessTypeModal.id = '';
    if (!id) {
      return;
    }
    this.loveRecycManageService.getRecycleModelList({seriesId: id, page: 1, pageSize: 9999}).then((res: any) => {
      if (res.code === 0) {
        this.copyAssessTypeModal.typeOptions = res.data.records;
      }
    });
  }

  export() {

    this.nzModalService.confirm({
      nzTitle: '提示',
      nzContent: '即将导出符合本页面筛选条件的订单数据，为了导出速度请尽可能控制时间范围。确定导出？',
      nzOkText: '确定',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: async () => {
        const params = {
          name: this.query.typeName,
          brandId: this.query.brand,
          seriesId: this.query.department,
          evalId: this.query.template,
          remarks: this.query.remarks,
          evalStatus: this.query.evalStatus,
          startTime: this.assessPriceService.formatTime(this.query.date[0], 'date'),
          endTime: this.assessPriceService.formatTime(this.query.date[1], 'date')
        };
        this.assessPriceService.getOrderExcel(params)
          .then((res: any) => {
            const name = decodeURI(res.headers.get('content-disposition').replace('attachment; filename=', ''));
            if (res.body.type === 'application/octet-stream') {
              const blob = new Blob([res.body], {type: 'application/vnd.ms-excel'});
              const objectUrl = URL.createObjectURL(blob);
              const a = document.createElement('a');
              a.href = objectUrl;
              a.download = name;
              a.target = '_blank';
              a.click();
              URL.revokeObjectURL(a.href);
              a.remove();
            } else {
              this.nzMessageService.error('导出失败');
            }
          });
      },
      nzCancelText: '关闭'
    });
  }

  // 导出基准价
  exportBenchmarkPrice() {
    this.nzModalService.confirm({
      nzTitle: '提示',
      nzContent: '即将导出符合本页面筛选条件的数据，为了导出速度请尽可能的控制时间范围。确认导出？',
      nzOkText: '确认',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: async () => {
        const params = {
          name: this.query.typeName,
          brandId: this.query.brand,
          seriesId: this.query.department,
          evalId: this.query.template,
          remarks: this.query.remarks,
          evalStatus: this.query.evalStatus,
          startTime: this.assessPriceService.formatTime(this.query.date[0], 'date'),
          endTime: this.assessPriceService.formatTime(this.query.date[1], 'date')
        };
        this.exportBenchmarkPriceLoading = true;
        const res: any = await this.assessPriceService.exportModelBenchmarkPriceData(params);
        this.exportBenchmarkPriceLoading = false;

        if (res.type === 'application/octet-stream') {
          this.commonService.downLoadBlobFile(res, '机型估价-基准价');
        } else {
          this.nzMessageService.error('导出失败');
        }
      },
      nzCancelText: '取消'
    });
  }
}
